import { createRef, RefObject, useEffect, useState } from 'react'
import { useMemoizedFn } from 'ahooks'
import { Button, Card, message, Typography, Upload, UploadProps } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import { ColDef, ICellRendererParams } from '@ag-grid-community/core'
import { AgGridReact } from '@ag-grid-community/react'

import { CusAgGrid } from '@/components/CusAgGrid'
import { fileValidate } from '@/utils/utils'
import { apiGetBoxNumberMapInformation, apiImportBoxNumberMap } from '../../apis'
import { IGetBoxNumberMapInformationReq } from '../../interface'
import { useUrlParams } from '../../utils'
import styles from './styles.module.less'

const columnDefs: ColDef<IGetBoxNumberMapInformationReq>[] = [
  {
    headerName: '序号',
    cellRenderer: (params: ICellRendererParams) => (params.node?.rowIndex ?? -1) + 1,
  },
  {
    field: 'fbaBoxNumber',
    headerName: 'FBA箱号',
  },
  {
    field: 'trackingNumber',
    headerName: '物流单号',
  },
  {
    field: 'carrier',
    headerName: '物流公司',
  },
  {
    field: 'masterWaybillNo',
    headerName: '母单号',
  },
  {
    field: 'latestRouting',
    headerName: '最新路由',
  },
]

export const ContainerNumber = () => {
  const { waybillNo } = useUrlParams()
  const gridRef: RefObject<AgGridReact<any>> = createRef()
  const [rowData, setRowData] = useState<any[]>([])

  const getContainerNumberMapInformation = useMemoizedFn(async () => {
    const res = await apiGetBoxNumberMapInformation({ waybillNo })
    setRowData(res || [])
  })

  const uploadProps: UploadProps = {
    name: 'file',
    accept: fileValidate.EXCEL_ACCEPT,
    showUploadList: false,
    customRequest: async options => {
      const { file, onError, onSuccess } = options
      try {
        await apiImportBoxNumberMap({ file: file as File, waybillNo })
        message.success(`${(file as any).name} 文件上传成功`)
        onSuccess?.({})
        // 上传成功后刷新映射数据
        await getContainerNumberMapInformation()
      } catch (err) {
        message.error(`${(file as any).name} 文件上传失败`)
        onError?.(err instanceof Error ? err : new Error('upload failed'))
      }
    },
  }

  useEffect(() => {
    getContainerNumberMapInformation()
  }, [])

  return (
    <Card>
      <div className={styles.container_header}>
        <Typography.Title level={5}>FBA箱号映射</Typography.Title>
        <Upload {...uploadProps}>
          <Button type="default" icon={<UploadOutlined />}>
            上传映射关系
          </Button>
        </Upload>
      </div>
      <div className={styles.container_grid}>
        <CusAgGrid<IGetBoxNumberMapInformationReq> ref={gridRef} rowData={rowData} columnDefs={columnDefs} />
      </div>
    </Card>
  )
}
